package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-08-15
 * Time: 21:57
 */
public class ThreadDemo13 {
    /*
    写一个代码，让主线程创建一个新的线程，由新的线程负责完成一系列运算（1+....+1000），由主线程负责获取到最终结果。
     */
    private static long result = 0;

    public static void main(String[] args) throws InterruptedException {
        /*Thread t = new Thread(()->{
            for (long i = 0; i <= 100_0000_0000L; i++) {
                result += i;
            }
        });
        t.start();
        //记录开始时间
        long start = System.currentTimeMillis();
        t.join();
        //记录结束时间
        long end = System.currentTimeMillis();
        System.out.println(result);
        System.out.println("耗时：" + (end - start)+"毫秒");*/
        //分成两个线程实现
        Thread t = new Thread(() -> {
            for (long i = 0; i <= 50_0000_0000L; i++) {
                result += i;
            }
        });
        Thread t1 = new Thread(() -> {
            for (long i = 50_0000_0001L; i <= 100_0000_0000L; i++) {
                result += i;
            }
        });
        t.start();
        t1.start();
        //记录开始时间
        long start = System.currentTimeMillis();

        t.join();//main主线程最后执行，在t线程结束之后再执行main线程
        t1.join();//在t1线程执行结束后在执行main线程

        //记录结束时间
        long end = System.currentTimeMillis();

        System.out.println("rusult = " + result);
        System.out.println("time = " + (end - start) + "毫秒");
    }
}
